package com.ceuer.demo.sync;

/*
不安全的线程问题
 */
class UnSafeBuyTicket {
	public static void main(String[] args) {
		BuyTicket buyTicket=new BuyTicket();
		new Thread(buyTicket,"张三").start();
		new Thread(buyTicket,"李四").start();
		new Thread(buyTicket,"黄牛党").start();
	}
}

class BuyTicket implements Runnable{
	// 票
	int ticketNums=10;
	boolean flag=true;//外部停止方式
	
	@Override
	public void run() {
		//买票
		while (flag){
			buy();
		}
	}
	
	//synchronized 同步锁的是方法
	private synchronized void buy(){
		if(ticketNums<=0){
			flag=false;
			return;
		}
		//模拟延迟
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//买票
		System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
	}
}